package com.fuego.creditsystemcommodity.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuego.creditsystemcommodity.mapper.HotelTypeMapper;
import com.fuego.creditsystemcommodity.service.IHotelTypeService;
import jakarta.annotation.Resource;
import org.example.dto.Result;
import org.example.entity.HotelType;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

import static org.example.utils.RedisConstants.CACHE_HOTELTYPE_KEY;


@Service
public class HotelTypeServiceImpl extends ServiceImpl<HotelTypeMapper, HotelType> implements IHotelTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        String key = CACHE_HOTELTYPE_KEY;
        // 1. 从 Redis 查询缓存
        String hotelTypeJson = stringRedisTemplate.opsForValue().get(key);

        // 2. 缓存存在，直接返回
        if (StrUtil.isNotBlank(hotelTypeJson)) {
            List<HotelType> hotelTypes = JSONUtil.toList(hotelTypeJson, HotelType.class);
            return Result.ok(hotelTypes);
        }

        // 3. 缓存不存在，查询数据库
        List<HotelType> hotelTypes = this.query()
                .orderByAsc("sort")
                .list();

        // 4. 数据库无数据，返回空列表
        if (hotelTypes == null || hotelTypes.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }

        // 5. 写入 Redis 并返回
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(hotelTypes));
        return Result.ok(hotelTypes);
    }

}
